package com.woniuxy.produce;

import org.springframework.amqp.core.ReturnedMessage;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class TopicProduce implements RabbitTemplate.ConfirmCallback,RabbitTemplate.ReturnsCallback{
    @Autowired
    private RabbitTemplate rabbitTemplate;

    public void send(String routeKey,String msg){
        rabbitTemplate.setConfirmCallback(this);
        rabbitTemplate.setReturnsCallback(this);
        CorrelationData correlationData = new CorrelationData();
        rabbitTemplate.convertAndSend("topicExchange",routeKey,msg,correlationData);
    }

    /**
     * 生产者与交换机
     * 交换机的回调函数
     * 作用：交换机通过该方法告诉生参者消息发送成功还是失败
     *
     * @param correlationData 生产者发送消息时封装的类，发送失败时可以利用该类重发
     * @param b 成功或失败的标识
     * @param s 失败的原因
     */
    @Override
    public void confirm(CorrelationData correlationData, boolean b, String s) {
        if(!b){
            //重发
        }
        System.out.println(correlationData);
        System.out.println(b);
        System.out.println(s);
    }


    /**
     * 交换机与队列
     * 队列回调方法，只有失败才会执行
     * @param returnedMessage
     */
    @Override
    public void returnedMessage(ReturnedMessage returnedMessage) {
        System.out.println(returnedMessage.getMessage());//发送消息
        System.out.println(returnedMessage.getExchange());//交换机名字
        System.out.println(returnedMessage.getReplyCode());//失败的状态码
        System.out.println(returnedMessage.getReplyText());//失败原因
        System.out.println(returnedMessage.getRoutingKey());//路由key
    }
}
